package com.atsmart.app.activity;

import javax.swing.text.Position.Bias;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.utils.DialogUtil;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.StringUtil;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.MKAddrInfo;
import com.baidu.mapapi.MKBusLineResult;
import com.baidu.mapapi.MKDrivingRouteResult;
import com.baidu.mapapi.MKPoiInfo;
import com.baidu.mapapi.MKPoiResult;
import com.baidu.mapapi.MKSearch;
import com.baidu.mapapi.MKSearchListener;
import com.baidu.mapapi.MKSuggestionResult;
import com.baidu.mapapi.MKTransitRouteResult;
import com.baidu.mapapi.MKWalkingRouteResult;
import com.baidu.mapapi.MapActivity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

public class LocMsgActivity extends MapActivity{
	private TextView loc_info, cell_info, location_info;
	private Context context;
	private Dialog dialog;
	// 定义地图引擎管理类  
    private BMapManager mapManager;  
    // 定义搜索服务类  
    private MKSearch mMKSearch;  
	// 地图相关
	// 搜索相关
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loc_msg_layout);
		context = this;
		dialog = DialogUtil.getLoadingDialog(context);
		loc_info = (TextView) findViewById(R.id.loc_infos);
		cell_info = (TextView) findViewById(R.id.cell_infos);
		location_info = (TextView) findViewById(R.id.location_infos);
		
		mapManager = new BMapManager(getApplication());  
        // init方法的第一个参数需填入申请的API Key  
        mapManager.init("53BD9B67787BE8DBF3B721511595184902D8B50C", null);  
        mapManager.getLocationManager();
        super.initMapActivity(mapManager);  
        
     // 初始化MKSearch  
        mMKSearch = new MKSearch();  
        mMKSearch.init(mapManager, new MySearchListener());  
        try{
			new AsyncTask<Void, Void, Void>() {
	
				@Override
				protected Void doInBackground(Void... params) {
					Message msg = new Message();
					msg.what = 0x001;
					handler.sendMessage(msg);
					start_end();
					return null;
				}
				
				@Override
				protected void onPostExecute(Void result) {
					Message msg = new Message();
					msg.what = 0x002;
					handler.sendMessage(msg);
					loc_info.setText("经度：" + (BizApp.getInstance().getLat() == 0.0 ? "无法获取经度" : BizApp.getInstance().getLat()) + "  , 纬度：" + (BizApp.getInstance().getLon() == 0 ? "无法获取纬度" : BizApp.getInstance().getLon()));
					String cellStr = "";
					if(!StringUtil.isEmptyOrNull(LocationUtils.getInstance().getLocationMsg())){
						cellStr = LocationUtils.getInstance().getLocationMsg();
					}
					if(!StringUtil.isEmptyOrNull(cellStr)){
						String[] strs = cellStr.split(",");
						cell_info.setText("移动国家代码:" + strs[0] + "\n移动网络号码:" + strs[1] + "\n位置区域码:" + strs[2] + "\n基站编号" + strs[3] + "\n系统标识:" + strs[4]);
					}else{
						cell_info.setText("无法获取基站信息");
					}
					
					GeoPoint ptCenter = new GeoPoint((int)((BizApp.getInstance().getLat())*1e6), (int)((BizApp.getInstance().getLon())*1e6));
					 mMKSearch.reverseGeocode(ptCenter);  
					super.onPostExecute(result);
				}
			}.execute();
        }catch (Exception e) {
		}
	}
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if(msg.what == 0x001){
				dialog.show();
			}else if(msg.what == 0x002){
				dialog.cancel();
			}
		};
	};
	private void start_end() {
		try{
		new Thread() {
				@Override
				public void run() {
					super.run();

					try {
						boolean ff = false;
						if ((BizApp.getInstance().isWiFiActive() || BizApp
								.getInstance().isNetworkAvailable())
								&& BizApp.getInstance().keeping) {
							if (BizApp.getInstance().getCurrentLocation() == null
									|| BizApp.getInstance().getLat() < 0.0001
									|| BizApp.getInstance().getLon() < 0.0001
									|| System.currentTimeMillis() > (BizApp
											.getInstance().getLocTime() + 70000)) {
								if (!BizApp.getInstance()
										.getmLocationClient().isStarted()) {
									BizApp.getInstance()
											.getmLocationClient().start();
								}
								try {
									sleep(7000);
									int i = 0;
									while (!BizApp.getInstance().isLocation
											&& i < 11) {
										sleep(4000);
										i++;
									}
									if (BizApp.getInstance().isLocation) {
										ff = true;
										BizApp.getInstance().isLocation = false;
									}
									BizApp.getInstance()
											.getmLocationClient().stop();
								} catch (InterruptedException e) {
								}
							} else {
								BizApp.getInstance().getmLocationClient()
										.stop();
							}
						}

					} catch (Exception e) {
					}
				}
			}.start();
		}catch (Exception e) {
		}
	}
	 @Override  
	    protected boolean isRouteDisplayed() {  
	        return false;  
	    }  
	  
	    @Override  
	    protected void onDestroy() {  
	        if (mapManager != null) {  
	            // 程序退出前需调用此方法  
	            mapManager.destroy();  
	            mapManager = null;  
	        }  
	        super.onDestroy();  
	    }  
	  
	    @Override  
	    protected void onPause() {  
	        if (mapManager != null) {  
	            // 终止百度地图API  
	            mapManager.stop();  
	        }  
	        super.onPause();  
	    }  
	  
	    @Override  
	    protected void onResume() {  
	        if (mapManager != null) {  
	            // 开启百度地图API  
	            mapManager.start();  
	        }  
	        super.onResume();  
	    }  
	  
	    /** 
	     * 内部类实现MKSearchListener接口,用于实现异步搜索服务 
	     *  
	     * @author liufeng 
	     */  
	    public class MySearchListener implements MKSearchListener {

			@Override
			public void onGetAddrResult(MKAddrInfo result, int arg1) {
				  if (result == null) {  
		                return;  
		            }  
					  try{
						  
			            StringBuffer sb = new StringBuffer();  
			            // 经纬度所对应的位置  
			            sb.append("经纬度所对应位置:").append("\r\r\n").append(result.strAddr).append("\n");
			            sb.append("商圈名称:"+result.strBusiness).append("\n");
//			            // 判断该地址附近是否有POI（Point of Interest,即兴趣点）  
//			            if (null != result.poiList) {  
//			                // 遍历所有的兴趣点信息  
//			                for (MKPoiInfo poiInfo : result.poiList) {  
//			                    sb.append("名称：").append(poiInfo.name).append("\n");  
//			                    sb.append("地址：").append(poiInfo.address).append("\n");  
//			                    sb.append("经度：").append(poiInfo.pt.getLongitudeE6() / 1000000.0f).append("\n");  
//			                    sb.append("纬度：").append(poiInfo.pt.getLatitudeE6() / 1000000.0f).append("\n");  
//			                    sb.append("电话：").append(poiInfo.phoneNum).append("\n");  
//			                    sb.append("邮编：").append(poiInfo.postCode).append("\n");  
//			                    // poi类型，0：普通点，1：公交站，2：公交线路，3：地铁站，4：地铁线路  
////			                    sb.append("类型：").append(poiInfo.ePoiType).append("\n");  
//			                }  
//			            }  
			            // 将地址信息、兴趣点信息显示在TextView上  
			           String str = "";
			           if(sb != null && sb.length() >0){
			        	   str = sb.toString();
			           }
			           location_info.setText(str);
				} catch (Exception e) {
				}
			}

			@Override
			public void onGetBusDetailResult(MKBusLineResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult arg0,
					int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetPoiDetailSearchResult(int arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetPoiResult(MKPoiResult arg0, int arg1, int arg2) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetRGCShareUrlResult(String arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetSuggestionResult(MKSuggestionResult arg0, int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult arg0,
					int arg1) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult arg0,
					int arg1) {
				// TODO Auto-generated method stub
				
			}  
	         
	    }  
	}  